package com.david.IfaceAutoTest.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jackson.JsonNodeReader;
import com.github.fge.jsonschema.core.report.LogLevel;
import com.github.fge.jsonschema.core.report.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

/**
 *   PostMan 导出文件格式校验
 *
 * @author david
 * @version 1.0
 * @date 2021/12/2110:23
 */
public class JsonSchemaUtil {
    public static void main(String[] args) throws IOException {
        String jsonStr = "";
        String filePath = "classpath:jsonSchema/test.json";
        System.out.println(getProcessingReport(jsonStr,filePath));

    }

    /**
     * @param jsonStr 验证json字符串
     */
    public static JsonNode strToJsonNode(String jsonStr) {
        JsonNode jsonNode = null;
        try {
            jsonNode = JsonLoader.fromString(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonNode;
    }

    /**
     * @param jsonFilePath jsonSchema文件路径
     */
    public static JsonNode schemaToJsonNode(String jsonFilePath) {
        JsonNode jsonSchemaNode = null;
        try {
            File file =ResourceUtils.getFile(jsonFilePath);
            jsonSchemaNode = new JsonNodeReader().fromReader(new FileReader(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonSchemaNode;
    }

    /**
     * @param jsonNodeStr   json数据node
     * @param schemaNodePath jsonSchema约束node
     */
    public static boolean getProcessingReport(String jsonNodeStr, String schemaNodePath) {
        JsonNode schemaNode=schemaToJsonNode(schemaNodePath);
        JsonNode jsonNode=strToJsonNode(jsonNodeStr);
        //fge验证json数据是否符合json schema约束规则
        ProcessingReport report = JsonSchemaFactory.byDefault().getValidator().validateUnchecked(schemaNode, jsonNode);
        if (report.isSuccess()) {
            // 校验成功
            return true;
        } else {
            Iterator<ProcessingMessage> it = report.iterator();
            StringBuilder ms = new StringBuilder();
            ms.append("json格式错误: ");
            while (it.hasNext()) {
                ProcessingMessage pm = it.next();
                if (!LogLevel.WARNING.equals(pm.getLogLevel())) {
                    ms.append(pm);
                }
            }
            System.err.println(ms);
            return false;
        }
    }
}
